package com.bdilab.iot.controller;

import com.bdilab.iot.annotation.CurrentUser;
import com.bdilab.iot.annotation.LogOperation;
import com.bdilab.iot.annotation.LogTag;
import com.bdilab.iot.common.ResultMap;
import com.bdilab.iot.consts.Constants;
import com.bdilab.iot.dto.roleDto.CreateRoleDto;
import com.bdilab.iot.dto.roleDto.RoleWithPermission;
import com.bdilab.iot.dto.roleDto.UpdateRoleDto;
import com.bdilab.iot.enums.OperationType;
import com.bdilab.iot.model.Permission;
import com.bdilab.iot.model.Role;
import com.bdilab.iot.model.User;
import com.bdilab.iot.service.RoleService;
import com.bdilab.iot.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * @author WangNing
 * @version 1.0
 * @date 2020/8/1 22:44
 */
@RestController
@Api(tags = "角色管理")
@RequestMapping(Constants.BASE_API_PATH )
@LogTag("角色管理")
public class RoleController {

    @Autowired
    TokenUtils tokenUtils;
    @Autowired
    RoleService roleService;

    @GetMapping("/all_role")
    @PreAuthorize("hasPermission('','超级管理员')")
    @ApiOperation(value = "查询全部角色", response =ResponseEntity.class)
    @LogOperation(operationName = "查询全部角色", operationType = OperationType.SELECT)
    public ResponseEntity getAllRole(HttpServletRequest request){
        ResultMap resultMap = new ResultMap(tokenUtils);
        List<Role> roles = roleService.getAllRole();
        resultMap.successAndRefreshToken(request).payload(roles);
        return ResponseEntity.ok(resultMap);
    }

    @PostMapping("/role")
    @PreAuthorize("hasPermission('','超级管理员')")
    @ApiOperation(value = "新建角色", response = ResponseEntity.class)
    @LogOperation(operationName = "新建角色", operationType = OperationType.INSERT)
    public ResponseEntity addRole(@CurrentUser @ApiIgnore User user,
                                  @RequestBody @Valid CreateRoleDto createRoleDto,
                                  @ApiIgnore BindingResult bindingResult,
                                  HttpServletRequest request){
        if (bindingResult.hasErrors()) {
            ResultMap resultMap = new ResultMap().fail().message(bindingResult.getFieldErrors().get(0).getDefaultMessage());
            return ResponseEntity.status(resultMap.getCode()).body(resultMap);
        }

        Role role = roleService.createRole(createRoleDto);
        ResultMap resultMap = new ResultMap(tokenUtils).successAndRefreshToken(request).payload(role);
        return ResponseEntity.ok(resultMap);

    }

    @DeleteMapping("/role/{id}")
    @PreAuthorize("hasPermission('','超级管理员')")
    @ApiOperation(value = "删除角色", response = ResponseEntity.class)
    @LogOperation(operationName = "删除角色", operationType = OperationType.DELETE)
    public ResponseEntity deleteRole(@CurrentUser @ApiIgnore User user,
                                     @PathVariable Long id,
                                     HttpServletRequest request){

        if(id <=0 ){
            ResultMap resultMap = new ResultMap(tokenUtils).failAndRefreshToken(request).message("无效的角色ID");
            return ResponseEntity.status(resultMap.getCode()).body(resultMap);
        }

        roleService.deleteRole(id);
        ResultMap resultMap = new ResultMap(tokenUtils).successAndRefreshToken(request);
        return ResponseEntity.ok(resultMap);
    }

    @PutMapping("/role/{id}")
    @PreAuthorize("hasPermission('','超级管理员')")
    @ApiOperation(value = "更新角色", response = ResponseEntity.class)
    @LogOperation(operationName = "更新角色", operationType = OperationType.UPDATE)
    public ResponseEntity deleteRole(@CurrentUser @ApiIgnore User user,
                                     @Valid @RequestBody UpdateRoleDto updateRoleDto,
                                     @ApiIgnore BindingResult bindingResult,
                                     @PathVariable Long id,
                                     HttpServletRequest request){
        if (bindingResult.hasErrors()) {
            ResultMap resultMap = new ResultMap().fail().message(bindingResult.getFieldErrors().get(0).getDefaultMessage());
            return ResponseEntity.status(resultMap.getCode()).body(resultMap);
        }

        if(id <=0 ){
            ResultMap resultMap = new ResultMap(tokenUtils).failAndRefreshToken(request).message("无效的角色ID");
            return ResponseEntity.status(resultMap.getCode()).body(resultMap);
        }

        Role  role = roleService.updateRole(updateRoleDto, id);
        ResultMap resultMap = new ResultMap(tokenUtils).successAndRefreshToken(request).payload(role);
        return ResponseEntity.ok(resultMap);
    }


    @GetMapping("/role/{id}")
    @PreAuthorize("hasPermission('','超级管理员')")
    @ApiOperation(value = "查询角色", response = ResponseEntity.class)
    @LogOperation(operationName = "查询角色", operationType = OperationType.SELECT)
    public ResponseEntity addRole(@CurrentUser @ApiIgnore User user,
                                  @PathVariable Long id,
                                  HttpServletRequest request){

        if(id <=0 ){
            ResultMap resultMap = new ResultMap(tokenUtils).failAndRefreshToken(request).message("无效的角色ID");
            return ResponseEntity.status(resultMap.getCode()).body(resultMap);
        }

        RoleWithPermission roleWithPermission = roleService.getRole(id);
        ResultMap resultMap = new ResultMap(tokenUtils).successAndRefreshToken(request).payload(roleWithPermission);
        return ResponseEntity.ok(resultMap);
    }





}
